package org.platform.lwc.auth.service;

import cn.hutool.core.bean.BeanUtil;
import org.platform.lwc.log.exception.ServiceException;
import org.platform.lwc.system.feign.ISysUserClient;
import org.platform.lwc.tool.api.R;
import org.platform.lwc.tool.auth.domain.LoginUser;
import org.platform.lwc.tool.auth.domain.SecurityUser;
import org.platform.lwc.tool.auth.constants.AuthMessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户管理业务类
 */
@Service
public class UserServiceImpl implements UserDetailsService {


    @Autowired
    private ISysUserClient sysUserClient;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        R<LoginUser> r = sysUserClient.userInfo(username);

        if (R.isNotSuccess(r)) {
            throw new ServiceException(r.getMessage());
        }else if (Objects.isNull(r.getData())){
            throw new UsernameNotFoundException(AuthMessageConstant.USERNAME_PASSWORD_ERROR);
        }
        SecurityUser securityUser = new SecurityUser(r.getData());
        if (!securityUser.isEnabled()) {
            throw new DisabledException(AuthMessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(AuthMessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(AuthMessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(AuthMessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}
